import { login, logout, getInfo } from "@/common/login/service/login";
import { getToken, setToken, removeToken, isExpired } from "@/utils/auth";
import router from "@/router/router";
import request from "@/api/request";

const user = {
  state: {
    ces_token_opt: getToken(),
    name: "",
    avatar:
      "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.ces_token_opt = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      // userInfo = {
      //   userId: "36467",
      //   pwd: "123456",
      //   deviceCode: "misakamikotoichi1"
      // };
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const data = response.data;
            setToken(data);
            commit("SET_TOKEN", data);
            // 后端获取菜单数据
            let testMenu = [
              {
                path: "/demo",
                component: "Layout",
                redirect: "/demo/eleTable",
                name: "demo",
                meta: {
                  title: "example",
                  icon: "el-icon-menu"
                },
                children: [
                  {
                    path: "eleTable",
                    name: "eleTable",
                    component: "eleTable",
                    meta: {
                      title: "eleTable",
                      icon: "el-icon-menu",
                      noCache: false
                    }
                  },
                  {
                    path: "editTable",
                    name: "editTable",
                    component: "editTable",
                    meta: {
                      title: "封装可编辑表格",
                      icon: "el-icon-menu",
                      noCache: false
                    }
                  }
                ]
              }
            ];
            window.localStorage.setItem("menu", JSON.stringify(testMenu));
            // 后端获取菜单数据
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //刷新token
    async refreshToken({ commit, state }, opt) {
      if (!state.ces_token_opt) {
        return false;
      }
      //刷新token过期时间
      let refresh_token_exipre_time =
        state.ces_token_opt.refresh_token_exipre_time;
      let access_token_exipre_time =
        state.ces_token_opt.access_token_exipre_time;
      if (isExpired(refresh_token_exipre_time)) {
        //刷新token过期跳转登录页面
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        removeToken();
        router.push("/login");
      } else if (isExpired(access_token_exipre_time)) {
        //accesstoken过期，刷新它，重新存一下
        const { data } = await request({
          url: "/mobile/refreshToken",
          method: "post",
          data: {
            token: state.ces_token_opt.refresh_token
          }
        });
        if (data && data.access_token) {
          var ces_token_opt = JSON.parse(JSON.stringify(state.ces_token_opt));
          ces_token_opt.access_token = data.access_token;
          ces_token_opt.access_token_exipre_time =
            data.access_token_exipre_time;
          //重新设置新的token过期时间
          commit("setToken", ces_token_opt);
          opt.config.headers["Authorization"] = ces_token_opt.access_token;
          opt.resolve(opt.config);
        }
      }
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.ces_token_opt)
          .then(response => {
            const data = response.data;
            if (data.roles && data.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", data.roles);
            } else {
              reject("getInfo: roles must be a non-null array !");
            }
            commit("SET_NAME", data.name);
            commit("SET_AVATAR", data.avatar);
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.ces_token_opt)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            removeToken();
            window.localStorage.removeItem("menu");
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        removeToken();
        window.localStorage.removeItem("menu");
        resolve();
      });
    }
  }
};

export default user;
